<?php
namespace Common\Model;

/**
 * Todo:按s_d_domain建唯一索引
 */

class SiteDomainModel extends Model {
    protected $tableName = 'site_domain';
    protected $pk        = 's_d_id';

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = 'site_id DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if(empty($field)) {
            $field = array(
                'uid'         => 'uid',
                'user_name'   => 'user_name',
                'plan_type'   => 'plan_type',
                'zone_id'     => 'zone_id',
                'zone_width'  => 'zone_width',
                'zone_height' => 'zone_height',
                'zone_type'   => 'zone_type',
            );
        }

        foreach($field as $k => $v) {
            $val = isset($d[$k]) ? trim($d[$k]) : '';

            if(strlen($val) < 1) {
                continue;
           }

            switch($k) {
                case 'user_name' :
                    $expr['user_name'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                default:
                    $expr[$v] = $d[$k];
            }

            $dao[$k] = $d[$k];
        }

        /**
         * 处理多个查询项目合并到一起，然后只能选一项查询的情况
         * 保存到$dao中，用于回填至查询表单
         */
        foreach($d as $k => $v) {
            if(substr($k, 0, 12) == 'search_item_') {
                $dao[$k] = $v;
            }
        }

        /**
         * 因为部分查询会涉及到视图，所以需要在下面指定完整的可排序字段
         */
        $sortField = array('uid', 'plan_type', 'zone_type', 'zone_id', 'size', 'user_name');

        if(!empty($d['sort']) && in_array($d['sort'], $sortField)) {
            $sortdir = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';

            if($d['sort'] == 'size') {
                $sort     = 'size';
                $sortExpr = "zone_width {$sortdir}, zone_height {$sortdir}";
            } else {
                $sort     = $d['sort'];
                $sortExpr = "{$sort} {$sortdir}";
            }

            $dao['sort']    = $sort;
            $dao['sortdir'] = $sortdir;
        }

        return array(
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        );
    }

    public function save2($d) {
        $action = 'save';
        $id     = null;

        if(!empty($d['s_d_domain'])) {
            $tmpDomain = filterDomain($d['s_d_domain']);    //过滤掉网址中多余的信息只返回主机名

            /**
             * 验证域名合法性
             */
            if(!isSafeDomainString($tmpDomain)) {
                throw new ThinkException('请输入正确的网址');
            }

            $d['s_d_domain'] = $tmpDomain;
        }

        if(empty($d[$this->pk])) {
            if(empty($d['site_id'])) {
                throw new ThinkException('没有网站编号，无法保存网址');
            }

            if(!D2('Site')->getBySiteId($d['site_id'])) {
                throw new ThinkException('网站编号有误');
            }

            if(empty($d['s_d_domain'])) {
                throw new ThinkException('请输入网址');
            }

            $action = 'add';
        } else {
            $id = (int)$d['s_d_id'];
        }

        if(!empty($d['s_d_domain']) && $this->checkDominExists($d['s_d_domain'], $id)) {
            throw new ThinkException($d['s_d_domain'] . '网址已经存在');
        }

        if(!$r = $this->$action($d)) {
            return $r;
        }

        if(empty($d['site_id'])) {
            if(!$rSiteDomain = $this->getBySDId($d['s_d_id'])) {
                return $r;
            }

            $siteId = $rSiteDomain['site_id'];
        } else {
            $siteId = $d['site_id'];
        }

        try {
            cacheApi('site', $siteId);
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }

        return $r;
    }

    /**
     * checkDominExists
     * 检测域名是否已经存在
     *
     * 返回值true表示已存在，false表示不存在
     *
     * @param mixed $domain
     * @param mixed $id
     * @return void
     */
    public function checkDominExists($domain, $id = null) {
        $expr = array('s_d_domain' => $domain);

        if(!empty($id)) {
            $expr['s_d_id'] = array('NEQ', $id);
        }

        return $this->where($expr)->find();
    }

    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($id) {
        $id = (int)$id;

        if(!$record = $this->getBySDId($id)) {
            return true;
        }

        $expr = array(
            's_d_id' => $id,
        );

        return $this->where($expr)->delete();
    }

    /**
     * changeStatus
     * 改变域名状态
     *
     * @param mixed $d = array('s_d_id' => '域名编号', 's_d_status' => '域名状态’)
     * @return void
     */
    public function changeStatus($d) {
        if(empty($d['s_d_id']) || !isset($d['s_d_status'])) {
            throw new ThinkException('参数不完整');
        }

        $d['s_d_id']     = (int)$d['s_d_id'];
        $d['s_d_status'] = (int)$d['s_d_status'];

        if(!$record = $this->getBySDId($d['s_d_id'])) {
            throw new ThinkException('没有找到指定网址');
        }

        $dao = array(
            's_d_id'     => $d['s_d_id'],
            's_d_status' => $d['s_d_status'],
        );

        if(!$this->save($dao)) {
            return false;
        }

        try {
            cacheApi('site', $record['site_id']);
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }

        return true;
    }

}
